import React, { useState, useEffect } from 'react';
import { Card, Input, Button, List, Avatar, message, Modal } from 'antd';
import { LikeOutlined, MessageOutlined, WarningOutlined } from '@ant-design/icons';
import styles from './index.module.css';
import { submitComment, fetchComments, submitReply,likeComment } from '@/services/auth';

const { TextArea } = Input;

interface CommentItem {
  id: string;
  content: string;
  user: {
    name: string;
    avatar: string;
  };
  likes: number;
  replies: CommentItem[];
  createdAt: string;
}

const CommentsPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [commentContent, setCommentContent] = useState('');
  const [comments, setComments] = useState<CommentItem[]>([]);
  const [replyModalVisible, setReplyModalVisible] = useState(false);
  const [currentComment, setCurrentComment] = useState<CommentItem | null>(null);
  const [replyContent, setReplyContent] = useState('');
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}');

  useEffect(() => {
    loadComments();  // 移除用户邮箱检查，始终加载评论
  }, []);

  const loadComments = async () => {
    setLoading(true);
    try {
      const response = await fetchComments();
      // 按时间倒序排列评论
      const sortedComments = response.sort((a: CommentItem, b: CommentItem) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
      setComments(sortedComments || []);
    } catch (error) {
      message.error('获取评论失败');
      console.error('获取评论失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    if (!commentContent.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    if (!currentUser.email) {
      message.warning('请先登录');
      return;
    }

    try {
      const response = await submitComment({
        content: commentContent,
        user_id: currentUser.id,
        user_email: currentUser.email,
        user_name: currentUser.name || currentUser.email.split('@')[0] // 如果没有name就使用邮箱前缀
      });
      
      if (response) {
        await loadComments();
        setCommentContent('');
        message.success('评论成功');
      }
    } catch (error) {
      message.error('评论失败');
      console.error('评论提交失败:', error);
    }
  };

  // 处理点赞
  const handleLike = async (commentId: string) => {
    try {
      const response = await likeComment(commentId);
      const updatedComments = comments.map(comment => {
        if (comment.id === commentId) {
          return { ...comment, likes: response.likes };
        }
        return comment;
      });
      setComments(updatedComments);
      message.success('点赞成功');
    } catch (error) {
      message.error('点赞失败');
      console.error('点赞失败:', error);
    }
  };

  // 处理回复
  const handleReply = (comment: CommentItem) => {
    setCurrentComment(comment);
    setReplyModalVisible(true);
  };

  // 提交回复
  const handleReplySubmit = async () => {
    if (!replyContent.trim() || !currentComment) {
      message.warning('请输入回复内容');
      return;
    }

    try {
      const response = await submitReply(currentComment.id, replyContent);
      
      const updatedComments = comments.map(comment => {
        if (comment.id === currentComment.id) {
          return {
            ...comment,
            replies: [...comment.replies, response],
          };
        }
        return comment;
      });
  
      setComments(updatedComments);
      setReplyContent('');
      setReplyModalVisible(false);
      message.success('回复成功');
    } catch (error) {
      message.error('回复失败');
      console.error('回复提交失败:', error);
    }
  };

  return (
    <div className={styles.container}>
      <Card 
        title="评论区" 
        variant="default"
      >
        <div className={styles.commentInput}>
          <TextArea
            rows={4}
            value={commentContent}
            onChange={e => setCommentContent(e.target.value)}
            placeholder="请输入您的评论..."
          />
          <Button 
            type="primary" 
            onClick={handleSubmit}
            className={styles.submitButton}
          >
            发表评论
          </Button>
        </div>

        <List
          className={styles.commentList}
          loading={loading}
          itemLayout="vertical"
          dataSource={comments}
          renderItem={item => (
            <List.Item
              key={item.id}
              actions={[
                <span key="like" onClick={() => handleLike(item.id)} style={{ cursor: 'pointer' }}>
                  <LikeOutlined /> {item.likes}
                </span>,
                <span key="reply" onClick={() => handleReply(item)} style={{ cursor: 'pointer' }}>
                  <MessageOutlined /> 回复
                </span>,
                <span key="report"><WarningOutlined /> 举报</span>
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar src={item.user.avatar}>{item.user.name[0]}</Avatar>}
                title={item.user.name}
                description={item.createdAt}
              />
              {item.content}
              {item.replies.length > 0 && (
                <List
                  className={styles.replyList}
                  itemLayout="vertical"
                  dataSource={item.replies}
                  renderItem={reply => (
                    <List.Item key={reply.id}>
                      <List.Item.Meta
                        avatar={<Avatar src={reply.user.avatar}>{reply.user.name[0]}</Avatar>}
                        title={reply.user.name}
                        description={reply.createdAt}
                      />
                      {reply.content}
                    </List.Item>
                  )}
                />
              )}
            </List.Item>
          )}
        />
      </Card>

      <Modal
        title="回复评论"
        open={replyModalVisible}
        onOk={handleReplySubmit}
        onCancel={() => {
          setReplyModalVisible(false);
          setReplyContent('');
        }}
      >
        <Input.TextArea
          rows={4}
          value={replyContent}
          onChange={e => setReplyContent(e.target.value)}
          placeholder="请输入回复内容..."
        />
      </Modal>
    </div>
  );
};

export default CommentsPage;